package com.dangdi.util;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.CharBuffer;

public class SocketServer {

    private ServerSocket serverSocket;
    private Socket socket;
    private int port = 5055;

    private void start() throws Exception {
        serverSocket = new ServerSocket(port);
        while (true) {
            socket = serverSocket.accept();
            new Thread(new SocketThread(socket)).start();// 多线程阻塞
        }
    }

    /**
     * 处理socket连接s
     */
    class SocketThread implements Runnable {
        private Socket socket;
        private String temp = "";

        public SocketThread(Socket socket) {
            this.socket = socket;
        }

        @SuppressWarnings("unused")
        public void run() {
            try {
                Reader reader = new InputStreamReader(socket.getInputStream());
                Writer writer = new OutputStreamWriter(socket.getOutputStream());
                CharBuffer charBuffer = CharBuffer.allocate(1024);
                int readIndex = -1;
                while ((readIndex = reader.read(charBuffer)) != -1) {
                    charBuffer.flip();
                    temp += charBuffer.toString();
                    System.out.println("server-->" + temp);
                    writer.write("this is server");
                    writer.flush();

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    if (!socket.isClosed()) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }

    }

    public static void main(String[] args) {
        SocketServer s = new SocketServer();
        try {
            s.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}